<template>
  <div class="filesPage pdbt_100">
    <TipMsg msg="需要您提供以下投保资料，仅供投保使用。" />
    <div class="example-box">
      <span class="example-txt" @click="showExamplePop = true">
        (拍摄示例)
      </span>
    </div>
    <div :class="{ disabledForm: disabledEdit }" v-if="pageLoad">
      <div class="photoCells">
        <div class="headTit">
          <span>
            拍摄投保人
            <i class="ftc10">{{ applicant.name || "" }}</i> 证件照
          </span>
        </div>
        <div class="upCell">
          <uploadFileBox
            type="20"
            imgType="5"
            :imgSrc="imgSrc20_5"
            :target="applicant"
          ></uploadFileBox>
          <uploadFileBox
            type="20"
            imgType="6"
            :imgSrc="imgSrc20_6"
            :target="applicant"
          ></uploadFileBox>
        </div>
      </div>
      <!-- 被保人证件类型 21 5/6 -->
      <div class="photoCells" v-if="showBbrModel">
        <div class="headTit">
          <span> 拍摄被保人证件照 </span>
        </div>
        <div class="upCell" v-for="(item, index) in bbrImgList" :key="index">
          <template v-if="item.relationToAppnt != '4'">
            <uploadFileBox
              type="21"
              imgType="5"
              :imgSrc="item.imgSrc5"
              :target="item"
              :key="`bbr${index}-img5`"
            ></uploadFileBox>
            <uploadFileBox
              type="21"
              imgType="6"
              :imgSrc="item.imgSrc6"
              :target="item"
              :key="`bbr${index}-img6`"
            ></uploadFileBox>
          </template>
        </div>
      </div>
      <!-- 受益人证件类型 22 5//6 -->
      <div class="photoCells" v-if="syrCarameModule">
        <div class="headTit">
          <span>拍摄受益人证件照</span>
        </div>
        <div class="upCell" v-for="(item, index) in syrImgList" :key="index">
          <uploadFileBox
            type="22"
            imgType="5"
            :imgSrc="item.imgSrc5"
            :target="item"
            :key="`syr${index}-img5`"
          ></uploadFileBox>
          <uploadFileBox
            type="22"
            imgType="6"
            :imgSrc="item.imgSrc6"
            :target="item"
            :key="`syr${index}-img6`"
          ></uploadFileBox>
        </div>
      </div>
      <!-- 银行卡图片 31 7-->
      <div class="photoCells" v-if="bankPhoto == '1'">
        <div class="headTit">
          <span>拍摄银行卡照片</span>
        </div>
        <div class="mode2">
          <div class="mode1_cell2 warning-mode mt10">
            <p class="bank_num">
              银行卡号：<b>{{ payInfo.bankAccNo | fmtBankNum }}</b>
            </p>
            <div class="flex_ac mode1_desc2">
              <MsImgIcon size="16" name="tip" class="mr2" />
              请核对银行卡号与上传的银行卡影像是否一致
            </div>
          </div>
        </div>
        <div class="upCell">
          <uploadFileBox
            type="31"
            imgType="7"
            :imgSrc="imgSrc31_7"
          ></uploadFileBox>
        </div>
      </div>
      <!-- 病历图片 32 8-->
      <div class="photoCells" v-if="bingliModule">
        <div class="headTit">
          <span>拍摄健康或财务资料</span>
          <MsImgIcon
            size="16"
            name="tip"
            @click.native="showTips('imgSrc32_8')"
          />
        </div>
        <div class="up2Cell">
          <uploadMultiFileBox
            type="32"
            imgType="8"
            :imgSrc="imgSrc32_8"
          ></uploadMultiFileBox>
        </div>
      </div>
      <!-- 自拍照  与签字页非同一个接口 34 13,14,15 -->
      <div class="photoCells" v-if="selfieModule">
        <div class="headTit">
          <span>销售过程影像(自拍照)</span>
        </div>
        <div class="upCell">
          <uploadFileBox type="34" imgType="13" :imgSrc="imgSrc34_13" />
          <uploadFileBox
            type="34"
            imgType="14"
            :imgSrc="imgSrc34_14"
            v-if="selfiePhotos.hasBbr && !isBenren"
          />
          <!-- <uploadFileBox type="34" imgType="15" :imgSrc="imgSrc34_15" /> -->
        </div>
      </div>
      <!-- 自保件 签字步骤 33 9,10,11,12-->
      <div class="photoCells" v-if="selfInsuredModule">
        <div class="headTit">
          <span>
            {{ selfInsuredTip.title || `客户签署人身投保提示书影像` }}
          </span>
          <MsImgIcon size="16" name="question" @click.native="descPop = true" />
        </div>
        <div class="upCell">
          <uploadFileBox
            type="33"
            imgType="9"
            :imgSrc="imgSrc33_9"
          ></uploadFileBox>
          <uploadFileBox
            type="33"
            imgType="10"
            :imgSrc="imgSrc33_10"
          ></uploadFileBox>
          <uploadFileBox
            type="33"
            imgType="22"
            :imgSrc="imgSrc33_22"
            v-if="selfInsuredPhotos.imgSrc33_22 != void 0"
          >
          </uploadFileBox>
          <uploadFileBox
            type="33"
            imgType="11"
            :imgSrc="imgSrc33_11"
            v-if="selfInsuredPhotos.imgSrc33_11 != void 0"
          >
          </uploadFileBox>
          <uploadFileBox
            type="33"
            imgType="12"
            :imgSrc="imgSrc33_12"
            v-if="selfInsuredPhotos.imgSrc33_12 != void 0"
          >
          </uploadFileBox>
        </div>
      </div>
      <!-- 合众---关系证明  -->
      <!-- 36 投被保人关系影像 16 -->
      <div class="photoCells" v-if="showRelationAI">
        <div class="headTit">
          <!-- 投保人与被保人关系证明影像 -->
          <span>未成年人监护关系证明</span>
          <MsImgIcon
            size="16"
            name="tip"
            @click.native="showTips('imgSrc36_16')"
          />
        </div>
        <div>
          <div class="upCell">
            <uploadMultiFileBox
              type="36"
              imgType="16"
              :imgSrc="imgSrc36_16"
            ></uploadMultiFileBox>
          </div>
        </div>
      </div>
      <template v-if="showRelationSyr">
        <!-- 37 投保人受益人关系影像 17 -->
        <div class="photoCells">
          <div class="headTit">投保人受益人关系证明影像</div>
          <div>
            <div class="upCell">
              <uploadMultiFileBox
                type="37"
                imgType="17"
                :imgSrc="imgSrc37_17"
              ></uploadMultiFileBox>
            </div>
          </div>
        </div>
        <!-- 38 被保人受益人关系影像 18 -->
        <div class="photoCells">
          <div class="headTit">被保人受益人关系证明影像</div>
          <div>
            <div class="upCell">
              <uploadMultiFileBox
                type="38"
                imgType="18"
                :imgSrc="imgSrc38_18"
              ></uploadMultiFileBox>
            </div>
          </div>
        </div>
      </template>
    </div>

    <FooterBtns btnNum="1" @saveForm="saveInfosBefore" />

    <ExamplePop
      :showExamplePop="showExamplePop"
      @closeBtn="(value) => (showExamplePop = value)"
    ></ExamplePop>
    <van-popup v-model="descPop">
      <div style="width: 300px; min-height: 360px; padding-bottom: 10px">
        <div v-html="selfInsuredTip.text" class="pop-box"></div>
        <img
          :src="selfInsuredTip.img || `${imgUrlPath}/img/zibaojian.jpg`"
          alt=""
        />
      </div>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import uploadFileBox from "./components/uploadFileBox";
import uploadMultiFileBox from "./components/uploadMultiFileBox";
import ExamplePop from "./components/ExamplePop";
import { getOrderDetail, toArtificial } from "@/utils/functions.js";
import { accountCodeFormat } from "@/methods/format.js";
import pageDits from "@/config/page.js";

export default {
  name: "UploadImageFilesPage",
  data() {
    return {
      descPop: false,
      pageLoad: false,
      showRelationSyr: false,
      showIndent: "",
      showExamplePop: false,
      imgSrc20_5: "",
      imgSrc20_6: "",
      imgSrc21_5: "",
      imgSrc21_6: "",
      imgSrc31_7: "", //银行卡图片
      imgSrc32_8: "", //病历（多张）
      imgSrc33_9: "", //投保提示书第一页图片
      imgSrc33_10: "", //投保提示书第二页图片
      imgSrc33_22: "", // 投保提示书第三页
      imgSrc33_11: "", //投保提示书签字时图片
      imgSrc33_12: "", //投保提示书手持图片
      imgSrc34_13: "", //投保人销售过程影像
      imgSrc34_14: "", //被保人销售过程影像
      imgSrc34_15: "", //代理人销售过程影像
      imgSrc36_16: "", //投被保人关系影像（数组类型）
      imgSrc37_17: "", //投保人受益人关系影像（数组类型）
      imgSrc38_18: "", //被保人受益人关系影像（数组类型）
      bbrImgList: [],
      syrImgList: [],
    };
  },
  components: { uploadFileBox, uploadMultiFileBox, ExamplePop },
  computed: {
    ...mapGetters({
      specialEntity: "page/specialEntity",
      noticeAbnormal: "common/noticeAbnormal",
      selfInsuredPhotos: "dictionary/selfInsuredPhotos",
      selfInsuredRegions: "dictionary/selfInsuredRegions",
      selfInsuredTip: "dictionary/selfInsuredTip",
      medicalPhotos: "page/medicalPhotos",
      bnfPhotos: "page/bnfPhotos",
      selfiePhotos: "page/selfiePhotos",
      doubleRecordEwmApi: "page/doubleRecordEwmApi",
      minorCustodyCertificate: "page/minorCustodyCertificate",
      minorAge: "page/minorAge",
      bankPhoto: "page/bankPhoto",
      applicant: "insert/applicant",
      payInfo: "insert/payInfo",
      totalPrem: "insert/totalPrem",
      tbrPrvinCapital: "insert/tbrPrvinCapital",
      doubRecordForbid: "page/doubRecordForbid",
    }),
    syrCarameModule() {
      let res = false;
      if (this.bnfPhotos.isShow && this.syrImgList.length > 0) {
        res = true;
      }
      return res;
    },
    bingliModule() {
      let res = false;
      if (this.medicalPhotos.isShow) {
        res = true;
      }
      return res;
    },
    selfieModule() {
      let res = false;
      if (this.selfiePhotos.show) {
        res = true;
      }
      return res;
    },
    selfInsuredModule() {
      let res = false;
      if (
        this.selfInsuredPhotos &&
        Object.keys(this.selfInsuredPhotos).length > 0
      ) {
        const areaCheck = this.selfInsuredRegions;
        if (areaCheck.length > 0) {
          if (areaCheck.includes(this.tbrPrvinCapital)) {
            res = true;
          }
        } else if (this.compEngName == "yangguang") {
          if (this.payInfo.qsContSelfFlag == "0") {
            res = true;
          }
        }
      }
      return res;
    },
    isBenren() {
      let res = false;
      if (this.bbrImgList[0].relationToAppnt == "4") {
        res = true;
      }
      return res;
    },
    checkNoticeStatus() {
      let res = false;
      // 配置需要检测告知异常填写sensingNotice
      if (this.noticeAbnormal && this.sensingNotice) {
        res = true;
      }
      return res;
    },
    // 未成年
    showRelationAI() {
      let res = false;
      if (this.minorCustodyCertificate) {
        const fd2Obj = this.bbrImgList.find((e) => {
          const age = this.$GlobalFuns.userAge(e.birthDate);
          return age < this.minorAge;
        });
        if (fd2Obj) {
          res = true;
        }
      }
      return res;
    },
    showBbrModel() {
      let res = false;
      const notSelf = this.bbrImgList.filter(
        (ele) => ele.relationToAppnt != "4"
      );
      if (notSelf && notSelf.length > 0) {
        res = true;
      }
      return res;
    },
  },
  filters: {
    fmtBankNum(value) {
      return accountCodeFormat(value);
    },
  },
  async created() {
    this.pageLoad = true;
    this.bbrImgList = [];
    this.syrImgList = [];
    const res = await getOrderDetail(this.apiComParams);
    if (res.data) {
      let { insureds } = res.data;
      if (insureds) {
        const len = insureds.length;
        let syrList = [];
        for (let b = 0; b < len; b++) {
          const item = insureds[b];
          if (item.bnfs && item.bnfs.length > 0) {
            const len2 = item.bnfs.length;
            for (let s = 0; s < len2; s++) {
              const ele = item.bnfs[s];
              ele.syrToInsNo = `${b}`;
            }
            syrList = [...syrList, ...item.bnfs];
          }
        }
        this.syrImgList = syrList.filter((ele) => ele.isSame != "1");
        let list2 = JSON.parse(JSON.stringify(insureds));
        this.bbrImgList = list2.filter((ele) => ele.relationToAppnt != "4");
      }
    }
    this.getImgList().then((res) => (this.pageLoad = true));
  },
  mounted() {},
  methods: {
    async saveInfosBefore() {
      if (this.disabledEdit) {
        this.forbidChange();
        return;
      }
      let res = await this.getImgList();
      // 0.阻断性校验
      if (!this.imgSrc20_5) {
        return this.$toast("请上传投保人证件正面");
      }
      if (!this.imgSrc20_6) {
        return this.$toast("请上传投保人证件背面");
      }
      if (this.showBbrModel) {
        // 多被保人
        let check3Tip = "";
        const bbrLen = this.bbrImgList.length;
        for (let s = 0; s < bbrLen; s++) {
          const item = this.bbrImgList[s];
          if (!item.imgSrc5) {
            check3Tip = `请上传被保人【${item.name}】证件正面`;
            break;
          }
          if (!item.imgSrc6) {
            check3Tip = `请上传被保人【${item.name}】证件背面`;
            break;
          }
        }
        if (check3Tip) {
          return this.$toast(check3Tip);
        }
      }
      if (this.bankPhoto == "1" && !this.imgSrc31_7) {
        return this.$toast("请上传银行卡照片");
      }
      /* === 保存前预处理-->阻断校验 === */
      let check2Tip = "";
      // 自保件拍照(阳光) selfInsuredModule
      if (this.selfInsuredModule) {
        const check1 =
            this.selfInsuredPhotos.imgSrc33_22 != void 0 &&
            this.imgSrc33_22 == "",
          check2 =
            this.selfInsuredPhotos.imgSrc33_11 != void 0 &&
            this.imgSrc33_11 == "",
          check3 =
            this.selfInsuredPhotos.imgSrc33_12 != void 0 &&
            this.imgSrc33_12 == "",
          check4 = this.imgSrc33_10 == "" || this.imgSrc33_9 == "";
        if (check1 || check2 || check3 || check4) {
          check2Tip = `${
            check2Tip ? `${check2Tip}；` : ""
          }需上传客户签署人身投保提示书影像`;
        }
      }
      // 自拍照(利安) selfieModule
      if (this.selfieModule && this.selfiePhotos.isCheck == "1") {
        const check21 = this.imgSrc34_13 == "",
          check22 = !this.isBenren && this.imgSrc34_14 == "";
        if (check21 || check22) {
          check2Tip = `${
            check2Tip ? `${check2Tip}；` : ""
          }需上传销售过程影像(自拍照)`;
        }
      }
      if (check2Tip) {
        this.$dialog
          .alert({
            title: "提示",
            message: `${check2Tip}`,
            messageAlign: "left",
            confirmButtonColor: "#DA251E",
            getContainer: "body",
          })
          .then(() => {
            if (
              this.doubRecordForbid &&
              this.doubRecordForbid.includes(this.mainRiskCode)
            ) {
              // 阻断投保
            } else {
              this.goNextStep(data.code, data.msg);
            }
          });
        return;
      }
      /* === 保存前预处理-->非阻断校验 === */
      let checkTip = "";
      // 0.受益人
      const syrLen = this.syrImgList.length;
      if (syrLen > 0) {
        for (let s = 0; s < syrLen; s++) {
          const item = this.syrImgList[s];
          if (!item.imgSrc6 || !item.imgSrc5) {
            checkTip = `请上传受益人证件照`;
            break;
          }
        }
      }
      // 1.关系证明 + 告知异常
      if (this.showIndent && this.certificate.length === 0) {
        checkTip = `本单需要上传‘未成年监护证明’`;
      }
      if (this.checkNoticeStatus && this.imgSrc32_8.length === 0) {
        checkTip = `${
          checkTip ? `${checkTip}；` : ""
        }客户告知部分为是，需要上传‘健康或财务资料’`;
      }
      if (this.showRelationAI && this.imgSrc36_16.length === 0) {
        checkTip = `${
          checkTip ? `${checkTip}；` : ""
        }本单需要上传‘未成年人监护关系证明’`;
      }
      if (
        this.showRelationSyr &&
        (this.imgSrc37_17.length === 0 || this.imgSrc38_18.length === 0)
      ) {
        checkTip = `${
          checkTip ? `${checkTip}；` : ""
        }本单需要上传‘投/被保人与受益人关系证明’`;
      }
      // return this.$router.push("/billsure");
      if (checkTip) {
        this.$baseConfirm(
          `【${checkTip}】，否则保单可能会核保失败,是否继续`,
          () => {
            this.saveInfos();
          },
          null,
          "继续投保",
          "去上传"
        );
      } else {
        this.saveInfos(); // 正常流程
      }
    },
    saveInfos() {
      // 投保接口
      this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: this.apiComParams,
          apiName: "proposal",
          toast: true,
        })
        .then((data) => {
          if (data.needDouble === "1") {
            this.$dialog
              .alert({
                title: "双录提示",
                message:
                  "根据地区监管规定,此投保申请须双录（同步进行录音、录像）,请联系业务员使用《WE易保》投保和双录。",
                messageAlign: "left",
                confirmButtonColor: "#DA251E",
                confirmButtonText: "我已知晓",
                getContainer: "body",
              })
              .then(() => {
                if (
                  this.doubRecordForbid &&
                  this.doubRecordForbid.includes(this.mainRiskCode)
                ) {
                  // 阻断投保
                  this.applyDefry();
                } else {
                  this.goNextStep(data.code, data.msg);
                }
              });
          } else {
            this.goNextStep(data.code, data.msg);
          }
        });
    },
    applyDefry() {
      this.$http
        .post(
          "/ms-insure/api/bilaiduo/applyDaKuan",
          {
            workNum: this.workNum,
            userId: this.bldUserId,
            money: this.totalPrem,
          },
          {
            showDialog: false,
            json: true,
          }
        )
        .then((res) => {
          // console.log(res);
        });
    },
    async goNextStep(code, msg) {
      const res = await getOrderDetail(this.apiComParams);
      // 核保禁止修改--->判断页面跳转/能否修改信息
      if (res.data && res.data.flag !== void 0) {
        if (["-1", "1", "3", "4", "5", "6"].includes(res.data.flag)) {
          this.$store.commit("insert/SET_FORBID_ALTER", true);
        }
      }
      if (code === "-1") {
        this.$router.push("/billres");
      } else if (["1", "2", "3", "4", "6"].includes(code)) {
        this.$router.push("/billsure");
      }
    },
    // 人核
    renWriteApi() {
      this.$store.commit("updateLoad", true);
      toArtificial(this.apiComParams).then(
        ({ data }) => {
          this.$store.commit("updateLoad", false);
          this.$baseAlert(data.msg, () => {
            if (data.code === "1") {
              this.$router.push("/billsure");
            }
          });
        },
        (err) => {
          this.$store.commit("updateLoad", false);
        }
      );
    },
    // 显示上传提示
    showTips(type) {
      const desc = pageDits.photos[`${type}`];
      if (desc) {
        this.$store.commit("common/SET_FIELD_MEAN_CONT", {
          label: "温馨提示",
          desc,
        });
      }
    },
    /**
     * 获取影像件数据
     */
    async getImgList() {
      return new Promise((resolve, reject) => {
        // 构建 idNum -> index 的映射表，提高查找效率
        const syrMap = new Map(
          this.syrImgList.map((item, idx) => [item.idNum, idx])
        );
        const bbrMap = new Map(
          this.bbrImgList.map((item, idx) => [item.idNum, idx])
        );
        this.$store
          .dispatch("apis/comAdminApiRequest", {
            apiParams: this.apiComParams,
            apiName: "queryImgList",
          })
          .then((data) => {
            if (data.code === "1") {
              // 先给证件清空
              this.bbrImgList.forEach((item) => {
                item.imgSrc6 = "";
                item.imgSrc5 = "";
              });
              this.syrImgList.forEach((item) => {
                item.imgSrc6 = "";
                item.imgSrc5 = "";
              });
              if (data.imgList.length > 0) {
                data.imgList.forEach((element) => {
                  const { type, imgType, idNum, imgUrl } = element;
                  if (
                    type == "20" &&
                    imgType == "5" &&
                    this.applicant.idNum == idNum
                  ) {
                    this.imgSrc20_5 = imgUrl;
                  } else if (
                    type == "20" &&
                    imgType == "6" &&
                    this.applicant.idNum == idNum
                  ) {
                    this.imgSrc20_6 = imgUrl;
                  }
                  //此处图片 的先决条件是 非双录 移到src/views/sign/bill.vue 处理
                  else if (
                    ["31", "32", "33", "34", "36", "37", "38"].includes(type) &&
                    imgType &&
                    imgUrl
                  ) {
                    this[`imgSrc${type}_${imgType}`] = imgUrl;
                  } else if (type == "22") {
                    const idx = syrMap.get(idNum);
                    if (idx !== undefined) {
                      if (imgType === "6") {
                        this.$set(this.syrImgList[idx], "imgSrc6", imgUrl);
                      } else {
                        this.$set(this.syrImgList[idx], "imgSrc5", imgUrl);
                      }
                    }
                  }
                  //多被保人
                  else if (type == "21") {
                    const idx = bbrMap.get(idNum);
                    if (idx !== undefined) {
                      if (imgType === "6") {
                        this.$set(this.bbrImgList[idx], "imgSrc6", imgUrl);
                      } else {
                        this.$set(this.bbrImgList[idx], "imgSrc5", imgUrl);
                      }
                    }
                  }
                });
              }
              resolve();
            }
          });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.photoCells {
  margin: 0 10px 10px;
  border-radius: 15px;
  background-color: #ffffff;
  padding-bottom: 20px;

  .headTit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 40px;
    padding: 0 15px;
    font-weight: 500;
  }
}

.upCell {
  padding: 0 10px;
  display: flex;
  flex-wrap: wrap;
}

.up2Cell {
  padding: 0 10px;
}

.example-box {
  position: relative;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;

  .example-txt {
    line-height: 1;
    color: #18aeff;
  }
}

.mode2 {
  padding: 0 15px;
  margin-bottom: 10px;

  .mode1_cell2 {
    padding: 8px 10px;
    border-radius: 4px;

    .bank_num {
      color: #242424;
    }

    .mode1_desc2 {
      margin-top: 5px;
      line-height: 17px;
    }
  }
}

.pop-box {
  width: 100%;
  padding: 14px;
}
</style>
